package com.webSite.demo.cy.utils.controller;

import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

@Controller
@EnableAutoConfiguration
public class CaptchaController {

	private Producer kaptchaProducer=null;  
	
    @Autowired
    public void setCaptchaProducer(Producer kaptchaProducer) {  
        this.kaptchaProducer = kaptchaProducer;  
    }
    
    /**
     * 生成验证码
    * @Title: handleRequest  
    * @Description: TODO
    * @param @param request
    * @param @param response
    * @param @return
    * @param @throws Exception    参数  
    * @return ModelAndView    返回类型  
    * @throws
     */
    @RequestMapping("/kaptcha")  
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception{  
        response.setDateHeader("Expires",0);  
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");  
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");  
        response.setHeader("Pragma", "no-cache");  
        response.setContentType("image/jpeg");  
        String capText = kaptchaProducer.createText();
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);  
        BufferedImage bi = kaptchaProducer.createImage(capText);  
        ServletOutputStream out = response.getOutputStream();  
        ImageIO.write(bi, "jpg", out);
        try {  
            out.flush();  
        } finally {  
            out.close();  
        }  
        return null;  
    }

    /**
     * 测试验证码(登录操作)
    * @Title: loginKaptcha  
    * @Description: TODO
    * @param @param request
    * @param @return
    * @param @throws Exception    参数  
    * @return String    返回类型  
    * @throws
     */
    @RequestMapping("/loginKaptcha")
    public String loginKaptcha(HttpServletRequest request) throws Exception{  
    	String verifyCode=request.getParameter("verifyCode").toUpperCase();
    	System.out.println("页面传过来的验证码："+verifyCode);
    	String code = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        System.out.println("默认的验证码:"+code);
    	return "redirect:/";  
    }
}
